package dataDAOImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import dataConnector.Connector;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.IProductBatchCompDAO;
import dataDTO.ProductBatchCompDTO;

public class MySQLProductBatchCompDAO implements IProductBatchCompDAO {

	@Override
	public ProductBatchCompDTO getProductBatchComp(int pbId, int rbId)
			throws DALException {
		ResultSet rs = Connector.doQuery("SELECT*FROM produktbatchkomponent WHERE pb_id = " +pbId
				+" AND rb_id = " +rbId);
		try {
			if(!rs.first()) throw new DALException("The produktbatchcomponent " + pbId + " dont exist");
			return new ProductBatchCompDTO(rs.getInt(1), rs.getInt(2), rs.getDouble(3),
					rs.getDouble(4), rs.getInt(5));
		}
		catch (SQLException e) {throw new DALException(e); }
	}


	@Override
	public void createProductBatchComp(ProductBatchCompDTO productbatchcomponent)
			throws DALException {
			Connector.doUpdate(
					"INSERT INTO produktbatchkomponent(pb_id, rb_id, tara, netto, opr_id) VALUES "
					+ "(" + productbatchcomponent.getPbId() + ", '" + productbatchcomponent.getCbId() + "','" +
					productbatchcomponent.getTara() +"','" + productbatchcomponent.getNetto() +"','"+
					productbatchcomponent.getOprId() + "')");
	}
	@Override
	public void updateProductBatchComp(ProductBatchCompDTO productbatchcomponent)
			throws DALException {
			Connector.doUpdate("UPDATE produktbatchkomponent SET pb_id = '" +
			productbatchcomponent.getPbId() + "', rb_id = '" + productbatchcomponent.getCbId()
			+ "',tara = '" + productbatchcomponent.getTara() + "', netto = '" +
			productbatchcomponent.getNetto() +"', opr_id = '" + productbatchcomponent.getOprId()
			+ "' WHERE pb_id = "+ productbatchcomponent.getPbId() + " AND rb_id = "+ productbatchcomponent.getCbId());
	}

	@Override
	public List<ProductBatchCompDTO> getProductBatchCompList()
			throws DALException {
		List<ProductBatchCompDTO> list = new ArrayList<ProductBatchCompDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM produktbatchkomponent");
		try {
			while(rs.next())
			{
				list.add(new ProductBatchCompDTO(rs.getInt(1),rs.getInt(2),rs.getDouble(3),rs.getDouble(4),rs.getInt(5)));
			}
		}
		catch (SQLException e) { throw new DALException(e); }
		
		return list;
	}


	@Override
	public List<ProductBatchCompDTO> getProductBatchCompList(int pbId)
			throws DALException {
		List<ProductBatchCompDTO> list = new ArrayList<ProductBatchCompDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM produktbatchkomponent WHERE pb_id = " + pbId);
		try{
			while(rs.next()){
				list.add(new ProductBatchCompDTO (rs.getInt(1),rs.getInt(2),rs.getDouble(3),rs.getDouble(4),rs.getInt(5)));
			}
		}
		catch(SQLException e) {throw new DALException(e);}
		return list;
	}
	}


